/**
 * 
 */
package hu.gbalage.owlforms.xforms.work;

import hu.gbalage.owlforms.api.Form;
import hu.gbalage.owlforms.xforms.XMLHelper;
import hu.gbalage.owlforms.xforms.gen.DescriptedXFormsSerializer;
import hu.gbalage.owlforms.xforms.gen.SerializeManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * @author balage
 *
 */
public class XFormsCache {

	public static Document generateXForms(URI formuri, URI[] inputs){
		File xforms = new File(WorkManager.tmp.getPath()+"/"+formuri.getFragment()+".xhtml");
		
		if (!xforms.exists()){
			Form form = FormsCache.getForm(formuri);
			SerializeManager formserializer = new SerializeManager(new DescriptedXFormsSerializer("/io"));
		
			Document doc = formserializer.serialize(form);
			
			try {
				XMLHelper.serialize(doc, new FileOutputStream(xforms));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return doc;
		}else{
			try {
				return XMLHelper.parse(new FileInputStream(xforms));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}
	
}
